import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import {toast} from "sonner";


// 创建 axios 实例
const api: AxiosInstance = axios.create({
  baseURL: process.env.NEXT_PUBLIC_API_BASE_URL || "http://localhost:3000/api",
  timeout: 10000,
});

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    // 添加请求头（如 token）
    const token = localStorage.getItem("token");
    if (token) {
      config.headers = config.headers || {};
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response: AxiosResponse) => {
    // 直接返回响应数据
      const { code, msg } = response.data;
      console.log(code, msg)
      if (code !== 200) {
          // 非成功状态码，抛出错误
          toast.error("消息提示", {
            description: msg
          })
          // alert(msg)
          // throw new Error(msg);
      }
    return response.data;

  },
  (error) => {
    // 统一错误处理
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 未授权，跳转到登录页
          //window.location.href = "/login";
          break;
        case 404:
          // 资源未找到
          console.error("资源未找到", error);
          break;
        default:
          console.error("请求错误", error);
      }
    } else {
      console.error("网络错误", error);
    }
    return Promise.reject(error);
  }
);

// 封装常用方法
export const get = <T>(url: string, config?: AxiosRequestConfig): Promise<T> => {
  return api.get(url, config);
};

export const post = <T>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig
): Promise<T> => {
  return api.post(url, data, config);
};

export const put = <T>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig
): Promise<T> => {
  return api.put(url, data, config);
};

export const del = <T>(url: string, config?: AxiosRequestConfig): Promise<T> => {
  return api.delete(url, config);
};

export default api;